
package seeqpod;


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import javax.swing.JOptionPane;


public class InOut{
    private Exception Exception;
	SeeqPod sp = new SeeqPod();

        public int getsize(String address){
            int size = 0;
            try {
                URL url = new URL(address);
                URLConnection conn = url.openConnection();
                size = conn.getContentLength();
                conn.getInputStream().close();
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            return size;
        }
        
        public boolean urlisvalid(String address){
            try{
                URL url = new URL(address);
                URLConnection connection = url.openConnection();
                //connection.getInputStream().close();
            }catch(Exception e){
                return false;
            }
            return true;
        }
        
	public void download(String address, String localFileName) {	
            OutputStream out = null;
            URLConnection conn = null;
            InputStream  in = null;
		try {
                    URL url = new URL(address);
                    out = new BufferedOutputStream(new FileOutputStream(localFileName));
                    conn = url.openConnection();
                    in = conn.getInputStream();
                    byte[] buffer = new byte[1024];
                    int numRead;
                    long numWritten = 0;
                    while ((numRead = in.read(buffer)) != -1) {
                        out.write(buffer, 0, numRead);
                        numWritten += numRead;
                    }
                    System.out.println(localFileName + "\t" + numWritten);
		} catch (Exception exception) {
			exception.printStackTrace();
                        JOptionPane.showMessageDialog(null, "URL not valid, try another", "Oh no!", JOptionPane.INFORMATION_MESSAGE );
                        
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {}
                        
		}
	}
        public void download(String address, File F){
            	OutputStream out = null;
		URLConnection conn = null;
		InputStream  in = null;
		try {
			URL url = new URL(address);
			out = new BufferedOutputStream(
				new FileOutputStream(F));
			conn = url.openConnection();
			in = conn.getInputStream();
			byte[] buffer = new byte[1024];
			int numRead;
			long numWritten = 0;
			while ((numRead = in.read(buffer)) != -1) {
				out.write(buffer, 0, numRead);
				numWritten += numRead;
			}
			System.out.println(F.getPath() + "\t" + numWritten);
		} catch (Exception exception) {
			exception.printStackTrace();
                        F.delete();
                        JOptionPane.showMessageDialog(null, F.getName() + ": URL not valid, try another one", "Oh no!", JOptionPane.INFORMATION_MESSAGE );
                        
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (IOException ioe) {
			}
		}
        }

         SeeqPodTrack SearchSeeqResult(String query, String KEY, int startIndex) throws Exception{

            BufferedReader in = null;
            SeeqPodTrack track = new SeeqPodTrack();
            String results = "";
            try{
                query = query.replaceAll(" ", "%20");
                System.out.println("http://www.seeqpod.com/api/v0.2/" + KEY + "/music/search/" + query + "/" + startIndex + "/1");
                URL url = new URL("http://www.seeqpod.com/api/v0.2/" + KEY + "/music/search/" + query + "/" + startIndex + "/1");
                in = new BufferedReader(new InputStreamReader(url.openStream()));
                results = in.readLine();
            }catch(Exception e){
                e.printStackTrace();
            }
            String location = results.substring(results.indexOf("<location>") + 10, results.indexOf("</location>"));

            if(urlisvalid(location)){
                String album;
                if (results.indexOf("<album>") != -1 && results.indexOf("<album>") < results.indexOf("</track>"))
                    album = results.substring(results.indexOf("<album>") + 7, results.indexOf("</album>"));
                else
                    album = "";
                
                String Genre;
                if (results.indexOf("<genre>") != -1 && results.indexOf("<genre>") < results.indexOf("</genre>")) 
                    Genre = results.substring(results.indexOf("<genre>") + 7, results.indexOf("</genre>"));
                else
                    Genre = "";
                track.setAll(location, results.substring(results.lastIndexOf("<title>") + 7, results.lastIndexOf("</title>")), results.substring(results.indexOf("<creator>") + 9, results.indexOf("</creator>")), album, Genre, startIndex);
            }
            else
                throw Exception;
            
            return track;
            
        }
	
        SeeqPodTrack[] SearchSeeqResults(String query, String KEY, int startIndex, int numResults){
            ArrayList<SeeqPodTrack> tracklist = new ArrayList<SeeqPodTrack>(numResults);
            
            BufferedReader in = null;
            String results = "";
            try{
                query = query.replaceAll(" ", "%20");
                URL url = new URL("http://www.seeqpod.com/api/v0.2/" + KEY + "/music/search/" + query + "/" + startIndex + "/1");
                in = new BufferedReader(new InputStreamReader(url.openStream()));
                results = in.readLine();
            }catch(Exception e){
                e.printStackTrace();
            }
            //int start = Integer.parseInt(results.substring(results.indexOf(" start=\"") + 8, results.indexOf("\" end=")));
            //int end = Integer.parseInt(results.substring(results.indexOf(" end=\"") + 6, results.indexOf("\" total=")));
            // numResults =  end - start + 1;
            int total = Integer.parseInt(results.substring(results.indexOf("total=\"") + 7, results.indexOf("\" prev")));
            for(int i = 0; tracklist.size() < numResults && i < total; i++){
                try {
                    tracklist.add(SearchSeeqResult(query, KEY, i + startIndex));
                } catch (Exception ex) {
                    continue;
                }
            }
            numResults = tracklist.size();
            SeeqPodTrack trackarray[] = new SeeqPodTrack[numResults];
            for(int i = 0; i < numResults; i++)
                trackarray[i] = tracklist.get(i);
            return trackarray;
        }
        
        
        public SeeqPodRecommendation[] DiscoverSeeqResults(String artist, String song, String KEY){
		
    	download("http://www.seeqpod.com/api/v0.2/" + KEY + "/music/recommendations/artists/" + artist + "/" + song, "discover.xml");
		
		File f = new File("discover.xml");
		
		
		String str = null;
		try{
			BufferedReader in = new BufferedReader(new FileReader(f));
			str = in.readLine();
		}catch(IOException e){
			e.printStackTrace();
		}
		int total = 0, index =0;
		while(str.indexOf("<track>", index) > -1){
			total++;
			index = str.indexOf("<track>", index) + 7;
		}
		
		SeeqPodRecommendation recommend[] = new SeeqPodRecommendation[total];
		int trackindex = str.indexOf("</title>") + 8;
		
		for(int i = 0; i < total; i++){
			recommend[i] = new SeeqPodRecommendation();
			recommend[i].setLocation(str.substring(str.indexOf("<location>", trackindex) + 10, str.indexOf("</location>", trackindex)));
			recommend[i].setTitle(str.substring(str.indexOf("<title>", trackindex) + 7, str.indexOf("</title>", trackindex)));
			recommend[i].setCreator(str.substring(str.indexOf("<creator>", trackindex) + 9, str.indexOf("</creator>", trackindex)));
			if(str.indexOf("<album>", trackindex) != -1 && str.indexOf("<album>", trackindex) < str.indexOf("</track>", trackindex))
				recommend[i].setAlbum(str.substring(str.indexOf("<album>", trackindex) + 7, str.indexOf("</album>", trackindex)));
			
			if(str.indexOf("<genre>", trackindex) != -1 && str.indexOf("<genre>", trackindex) < str.indexOf("</genre>", trackindex))
				recommend[i].setGenre(str.substring(str.indexOf("<genre>", trackindex) + 7, str.indexOf("</genre>", trackindex)));
			recommend[i].setSeeqPodTrack();
			trackindex = str.indexOf("</track>", trackindex) + 8;
		}
		return recommend;
	}
	
	public SeeqPodSpellCheck[] SeeqPodSpell(String query, String KEY){
		download("http://www.seeqpod.com/api/v0.2/" + KEY + "/music/spellcheck/" + query, "spell.xml");
		
		File f = new File("spell.xml");
		
		StringBuilder str1 = new StringBuilder(5000);
		
		try{
			BufferedReader in = new BufferedReader(new FileReader(f));
			String line = in.readLine();
			for(int count = 0; line != null; count++){
				str1.append(line);
				line = in.readLine();
			}
		}catch(IOException e){
			e.printStackTrace();
		}
		String str = str1.toString();
		int total = 0, index = 0;
		while(str.indexOf("<result>", index) > -1){
			total++;
			index = str.indexOf("<result>", index) + 8;
		}
		
		SeeqPodSpellCheck recommend[] = new SeeqPodSpellCheck[total];
		int trackindex = str.indexOf("<resultList>") + 12;
		for(int i = 0; i < total; i++){
			recommend[i] = new SeeqPodSpellCheck();
			recommend[i].setArtist(str.substring(str.indexOf("<artist>", trackindex) + 8, str.indexOf("</artist>", trackindex)));
			recommend[i].setScore((Float.parseFloat(str.substring(str.indexOf("<score>", trackindex) + 7, str.indexOf("</score>", trackindex)))));
						
			trackindex = str.indexOf("</result>", trackindex) + 8;
		}
		return recommend;
	}
	
}

